#include "register.h"
#include "ui_register.h"

Register::Register(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
    ui->lineEdit_username->setClearButtonEnabled(true);
    ui->lineEdit_password->setEchoMode(QLineEdit::Password);
    ui->lineEdit_password->setClearButtonEnabled(true);

    ui->lineEdit_check_password->setEchoMode(QLineEdit::Password);
    ui->lineEdit_check_password->setClearButtonEnabled(true);

    manager = new QNetworkAccessManager(this);
}

Register::~Register()
{
    delete ui;
}

void Register::on_pushButton_ok_clicked()
{
    if(ui->lineEdit_username->text() == "")
    {
        qDebug() << "用户名为空";
        return;
    }
    if(ui->lineEdit_password->text() == "")
    {
        qDebug() << "密码为空";
        return;
    }
    if(ui->lineEdit_password->text().size() < 6)
    {
        qDebug() << "密码长度小于六位";
        return;
    }
    if(ui->lineEdit_password->text() != ui->lineEdit_check_password->text())
    {
        qDebug() << "两次输入的密码不一样";
        return;
    }
    //httpClient* hc = new httpClient(this);
    //hc->http_req("/register", ui->lineEdit_username->text(), ui->lineEdit_password->text());
    //1.获取到输入框中的url
    QString name = "/register";
    QUrl url(URL + name);
    //2.构造一个HTTP请求对象
    QNetworkRequest request(url);
    //3.发送请求
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    //QNetworkReply* response = manager->get(request);
    //将请求进行反序列化
    QJsonObject req;//创建一个json对象
    req.insert("username", QJsonValue(ui->lineEdit_username->text()));
    req.insert("password", QJsonValue(ui->lineEdit_password->text()));
    response = manager->post(request, QJsonDocument(req).toJson());
    //4.通过信号槽，来处理函数
    connect(response, &QNetworkReply::finished, this, &Register::handle_resp);
}

void Register::on_pushButton_quit_clicked()
{
    qDebug() << "退出注册";
    this->close();
}
void Register::on_checkBox_clicked(bool checked)
{
    if(checked)
    {
        ui->lineEdit_password->setEchoMode(QLineEdit::Normal);
    }
    else
    {
        ui->lineEdit_password->setEchoMode(QLineEdit::Password);
    }
}

void Register::handle_resp()
{
    if(response->error() == QNetworkReply::NoError)
    {
        resp = response->readAll();
        qDebug() << "注册成功";
        //响应正确收取到了
        QMessageBox::information(this, "服务端响应", resp, QMessageBox::Ok);

        this->close();
    }
    else
    {
        resp = response->readAll();
        qDebug() << "handle_register:" << resp;
        qDebug() << "注册失败";
        //响应出错了
        QMessageBox::critical(this, "服务端响应", resp, QMessageBox::Ok);

    }
    //对response进行释放
    response->deleteLater();
}
